package m.toolkit.codegenerator;

import java.io.File;
import java.util.List;

import m.framework.controller.BaseController;
import m.framework.exception.SystemException;
import m.framework.template.TemplateUtil;
import m.framework.utils.FileUtil;
import m.toolkit.codegenerator.pdm.DataBase;
import m.toolkit.codegenerator.pdm.PdmParser;
import m.toolkit.codegenerator.pdm.Table;

import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**代码生成器*/
public class GeneratorFacade {
	private static Logger log = LoggerFactory.getLogger(GeneratorFacade.class);
	public static final String PROBJECT_ROOT_PKG=Config.PROBJECT_ROOT_PKG;
	
	public static void create(String tableName,String rootPkg,boolean overwrite,List<GeneratFileType> types) throws DocumentException{
		rootPkg = formatPkg(rootPkg);
		DataBase d=dataBase();
		log.debug("即将为表生成代码:"+tableName);
		for(Table t:d.getTables()){
			if(t.getCode().equals(tableName)){
				for(GeneratFileType type:types){
					singleTable(rootPkg,t, type,overwrite);
				}
			}else{
				log.debug("跳过表:"+t.getCode());
			}
		}
	}


	private static String formatPkg(String rootPkg) {
		if(rootPkg.startsWith(PROBJECT_ROOT_PKG)){
			rootPkg=rootPkg.substring(PROBJECT_ROOT_PKG.length()+1);
		}
		return rootPkg;
	}


	private static void singleTable(String pkg,Table table, GeneratFileType type,boolean overwrite) {
		String fileName=type.fileName(projectRoot(),pkg,table.modelName());
		log.debug("准备创建"+type);
		File file=new File(fileName);
		if(!overwrite&&file.exists()){
			throw new SystemException(fileName+"已经存在,请删除后再生成");
		}
		String tempalte=type.template();
		String content=TemplateUtil.parseTemplate(tempalte, new ClassConfig(table,pkg));
		FileUtil.createFile(fileName, content);
		log.debug("生成文件:"+fileName);
	}
	
	
	private static String projectRoot(){
		String file=GeneratorFacade.class.getResource("GeneratorFacade.class").getFile();
		int target=file.indexOf("target");
		return file.substring(0,target);
	}
	
	/**获取Config.PDM对应的文件信息*/
	public static DataBase dataBase() throws DocumentException{
		String pdm=GeneratorFacade.class.getResource(Config.PDM).getFile();
		PdmParser pp = new PdmParser();
		return pp.getDataBase(pdm);
	}


	/**
	 * 根据pdm内容生产java文件
	 * @param tableName pmd中的表名
	 * @param rootPkg 要生产代码的包名前缀例如:com.ota.base.permisson
	 * @param overwrite 如果文件已经存在是否要覆盖掉
	 * */
	public static void createJava(String tableName, String rootPkg,boolean overwrite) {
		try{
			create(tableName, rootPkg, overwrite, GeneratFileType.allClass());
		}catch(Exception ex){
			throw new SystemException("创建java文件失败",ex);
		}
	
	}

	/**
	 * 根据conttroller增,查,改页面
	 * @param overwrite 如果文件已经存在是否要覆盖 
	 * */
	public static void createPage(Class<? extends BaseController> controller,boolean overwrite) {
		CodeGenerator.createAll(controller, overwrite);
	}
}
